package common.utils
{
	/**
	 * @example
	 * var s:GSave = new GSave;
	 * s.bind("test");
	 * s.write("t","ds");
	 * trace(s.read("t")); 
	 */	
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;
	
	/**
	 * 对游戏数据的本地保存
	 * @author liuyong 
	 */	
	public class GSave extends Object
	{
		public var data:Object;

		public var name:String;

		protected var _so:SharedObject;

		public function GSave()
		{
			name = null;
			_so = null;
			data = null;
		}
		
		/**
		 * 绑定本地存储
		 * @param Name  存储名
		 * @return 
		 */		
		public function bind(Name:String):Boolean
		{
			name = null;
			_so = null;
			data = null;
			name = Name;
			try
			{
				_so = SharedObject.getLocal(name);
			}
			catch(e:Error)
			{
				name = null;
				_so = null;
				data = null;
				return false;
			}
			data = _so.data;
			return true;
		}
		
		/**
		 * 向绑定的空间写入数据
		 * @param FieldName
		 * @param FieldValue
		 * @param MinFileSize
		 * @return  
		 */		
		public function write(FieldName:String,FieldValue:Object,MinFileSize:uint=0):Boolean
		{
			if(_so == null)
			{
				return false;
			}
			data[FieldName] = FieldValue;
			return forceSave(MinFileSize);
		}
		
		/**
		 * 读取本地数据
		 * @param FieldName
		 * @return 
		 */		
		public function read(FieldName:String):Object
		{
			if(_so == null)
			{
				return null;
			}
			return data[FieldName];
		}
		
		public function forceSave(MinFileSize:uint=0):Boolean
		{
			if(_so == null)
			{
				return false;
			}
			var status:Object = null;
			try
			{
				status = _so.flush(MinFileSize);
			}
			catch (e:Error)
			{
				return false;
			}
			return status == SharedObjectFlushStatus.FLUSHED;
		}
		
		
		public function erase(MinFileSize:uint=0):Boolean
		{
			if(_so == null)
			{
				return false;
			}
			_so.clear();
			return forceSave(MinFileSize);
		}
	}
}
